package com.soul.admin.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.soul.commons.constans.Constants;
import com.soul.dubbo.api.db.UserApi;
import com.soul.dubbo.api.db.UserInfoApi;
import com.soul.dubbo.api.mongo.MovementApi;
import com.soul.dubbo.api.mongo.SmallVideoApi;
import com.soul.model.db.User;
import com.soul.model.db.UserInfo;
import com.soul.model.mongo.Movement;
import com.soul.model.vo.MovementsVo;
import com.soul.model.vo.PageResult;
import com.soul.model.vo.UserInfoVoAge;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManageService {

    @DubboReference
    private SmallVideoApi smallVideoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 分页查询用户信息
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult findPage(Long page, Long pageSize) {


        // 分页查询用户信息
        PageResult pageResult = userInfoApi.findPage(page, pageSize);
        // 获取分页结果集
        List<UserInfo> userInfoList = pageResult.getItems();
        // 转成vo
        List<UserInfoVoAge> voList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userInfoList)) {
            for (UserInfo userInfo : userInfoList) {
                UserInfoVoAge vo = new UserInfoVoAge();
                BeanUtils.copyProperties(userInfo, vo);
                String key = Constants.FREEZE_USER + userInfo.getId();
                if (StringUtils.isNotEmpty(stringRedisTemplate.opsForValue().get(key))){
                    vo.setUserStatus("2");
                }
                voList.add(vo);
            }
        }
        // 设置
        pageResult.setItems(voList);
        return pageResult;
    }

    /**
     * 查询用户详情
     *
     * @param userId
     * @return
     */
    public UserInfoVoAge findById(Long userId) {
        UserInfo userInfo = userInfoApi.findByUserIdUser(userId);
        UserInfoVoAge vo = new UserInfoVoAge();
        BeanUtils.copyProperties(userInfo, vo);
        // 前端时间是一个integer, 是一个时间戳
        vo.setCreated(userInfo.getCreated().getTime());
        String key = Constants.FREEZE_USER + userInfo.getId();
        if (StringUtils.isNotEmpty(stringRedisTemplate.opsForValue().get(key))){
            vo.setUserStatus("2");
        }
        return vo;
    }

    //查询指定用户发布的所有视频列表
    public PageResult findAllVideos(Long page, Long pagesize, Long uid) {
        return smallVideoApi.findByUserId(page, pagesize, uid);
    }

    //查询动态
    public PageResult findAllMovements(Long page, Long pagesize, Long uid, Integer state) {
        //1、调用API查询数据 ：Movment对象
        PageResult result = movementApi.findByUserId(uid, state, page, pagesize);
        //2、解析PageResult，获取Movment对象列表
        List<Movement> items = (List<Movement>) result.getItems();
        //3、一个Movment对象转化为一个Vo
        if (CollUtil.isEmpty(items)) {
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIdsAndCondition(userIds, null);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                vos.add(vo);
            }
        }
        //4、构造返回值
        result.setItems(vos);
        return result;
    }

    /**
     *  用户冻结操作
     *
     * @param userId             被冻结用户id
     * @param freezingTime       冻结时间，1为冻结3天，2为冻结7天，3为永久冻结
     * @param freezingRange      冻结范围，1为冻结登录，2为冻结发言，3为冻结发布动态
     * @param reasonsForFreezing 冻结原因
     * @param frozenRemarks      冻结备注
     * @return Map message作为key
     */
    public Map<String, String> freeze(String userId, String freezingTime, String freezingRange, String reasonsForFreezing, String frozenRemarks) {
        // 1. 根据冻结范围设置到redis中
        String key = Constants.FREEZE_USER + userId;
        Map<String, String> redisMap = new HashMap<>();
        redisMap.put("userId",userId);
        redisMap.put("freezingTime",freezingTime);
        redisMap.put("freezingRange",freezingRange);
        redisMap.put("reasonsForFreezing",reasonsForFreezing);
        redisMap.put("frozenRemarks",frozenRemarks);
        String freezeInfo = JSON.toJSONString(redisMap);
        switch (Integer.valueOf(freezingTime)){
            // 冻结3天
            case 1: stringRedisTemplate.opsForValue().set(key, freezeInfo,3, TimeUnit.DAYS);break;
            // 冻结7天
            case 2: stringRedisTemplate.opsForValue().set(key, freezeInfo,7, TimeUnit.DAYS);break;
            // 永久冻结
            case 3: stringRedisTemplate.opsForValue().set(key, freezeInfo);break;
            default:break;
        }
        // 2. 修改用户状态 用户状态,1为正常，2为冻结
        if (Integer.valueOf(freezingRange) == 1){
            User user = new User();
            user.setId(Long.valueOf(userId));
            user.setStatus(2);
            userApi.updateUserStatus(user);
        }
        // 3. 返回修改成功
        Map<String, String> map = new HashMap<>();
        map.put("message", "冻结用户账号成功了");
        return map;
    }

    /**
     *  用户解冻操作
     * @param userId  被解冻用户id
     * @param frozenRemarks 解冻备注 前端传值
     * @param reasonsForThawing 解冻原因 前端暂未传值
     * @return
     */
    public Map<String, String> unfreeze(String userId, String frozenRemarks, String reasonsForThawing) {
        // 1. 解冻用户 用户状态,1为正常，2为冻结
        String key = Constants.FREEZE_USER + userId;
        stringRedisTemplate.delete(key);
        User user = new User();
        user.setId(Long.valueOf(userId));
        user.setStatus(1);
        userApi.updateById(user);
        Map<String, String> map = new HashMap<>();
        map.put("message","解冻成功了");
        return map;
    }
}